import { ref, Ref } from 'vue'

/**
 * 防抖hook
 * @param fn 需要防抖的函数
 * @param delay 延迟时间，默认300ms
 * @returns 防抖后的函数
 */
export function useDebounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
): T {
  let timer: NodeJS.Timeout | null = null
  
  return ((...args: any[]) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }) as T
}

/**
 * 防抖状态hook
 * @param delay 延迟时间，默认300ms
 * @returns 防抖状态和防抖函数
 */
export function useDebounceState<T>(initialValue: T, delay: number = 300) {
  const state = ref<T>(initialValue) as Ref<T>
  let timer: NodeJS.Timeout | null = null
  
  const setState = (value: T) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      state.value = value
    }, delay)
  }
  
  return {
    state,
    setState
  }
} 